package cn.itcast.bos.service.system.impl;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.mapper.UserMapper;
import cn.itcast.bos.pagehelper.PageResult;
import cn.itcast.bos.service.system.UserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service("userServiceImpl")
@Transactional
public class UserServiceImpl implements UserService {

	/**
	 * ========================================
	 * @param page
	 * @param rows
	 * @return
	 */
	@Autowired
	private UserMapper userMapper;

	@Override
	public PageResult userListAndCondition(int page, int rows) {
		PageHelper.startPage(page,rows);
		Page<User> pages = (Page<User>) userMapper.selectUserListByCondition();
		return new PageResult(pages.getTotal(),pages.getResult());
	}

	@Override
	public void saveUser(User user, String[] roleIds) {
		// 保存用户
		userMapper.save(user);

		// 授予角色
		if (roleIds != null) {
			for (String roleId : roleIds) {
				userMapper.saveRoleAndUser(Integer.parseInt(roleId),user != null ? user.getId() : null);
			}
		}
	}

	@Override
	public List<Map<String, Object>> selectUserById(Integer id) {
		List<Map<String, Object>> maps = userMapper.selectUserById(id);
		System.out.println(maps.get(0).toString());
		return (maps != null && maps.size() > 0) ? maps : null;
	}

	@Override
	public void updateUser(User user, String[] roleIds) {
		// 保存用户
		userMapper.update(user);

		// 授予角色
		if (roleIds != null) {
			userMapper.delete(user != null ? user.getId() : null);
			for (String roleId : roleIds) {
				//先删除中间表数据,在重新添加:
				userMapper.saveRoleAndUser(Integer.parseInt(roleId),user != null ? user.getId() : null);
			}
		}
	}

	@Override
	public User findByUsername(String username) {
		return userMapper.findByUsername(username);
	}
}